package org.springcloud.plugin.framework.nacos.configuration;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.ribbon.NacosRibbonClientConfiguration;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.ServerList;
import org.springcloud.plugin.framework.listener.loadbalance.LoadBalanceListener;
import org.springcloud.plugin.framework.nacos.decorator.NacosServerListDecorator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.ConfigurableEnvironment;

import java.util.List;

/**
 * author: yanggld
 * date: 2019/12/14 18:30
 * version: 1.0
 * description: nacos负载均衡配置
 * 参考
 * com.alibaba.cloud.nacos.ribbon.RibbonNacosAutoConfiguration
 * @AutoConfigureAfter 若不配置，'com.netflix.client.config.IClientConfig' that could not be found.
 */
@Configuration
@AutoConfigureAfter(NacosRibbonClientConfiguration.class)
public class NacosLoadBalanceConfiguration {

    @Autowired
    private ConfigurableEnvironment environment;

    @Autowired
    private List<LoadBalanceListener> loadBalanceListeners;

    @Bean
    public ServerList<?> ribbonServerList(IClientConfig config, NacosDiscoveryProperties nacosDiscoveryProperties) {
        NacosServerListDecorator serverList = new NacosServerListDecorator(nacosDiscoveryProperties);
        serverList.initWithNiwsConfig(config);
        serverList.setEnvironment(environment);
        serverList.setLoadBalanceListeners(loadBalanceListeners);
        return serverList;
    }
}
